package com.action.gulimall.ware.service.impl;

import com.action.common.constant.WareConstant;
import com.action.gulimall.ware.entity.PurchaseDetailEntity;
import com.action.gulimall.ware.service.PurchaseDetailService;
import com.action.gulimall.ware.service.WareSkuService;
import com.action.gulimall.ware.vo.MergeVo;
import com.action.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;

import com.action.gulimall.ware.dao.PurchaseDao;
import com.action.gulimall.ware.entity.PurchaseEntity;
import com.action.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<PurchaseEntity>()
                .eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        //没有选择任何【采购单】，将自动创建新单进行合并。
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //设置采购单的默认状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());

            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);

            //获取新建采购单的id
            purchaseId = purchaseEntity.getId();

        }

        List<Long> items = mergeVo.getItems();

        //TODO 确认采购单状态是0,1才可以合并
        Collection<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(items);

        purchaseDetailEntities.forEach((item) -> {
            if (!item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())
                    && !item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())) {
                throw new IllegalArgumentException("正在采购，无法进行分配");
            }
        });

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        //批量修改
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
        ids.stream().map(id -> this.getById(id))
                .filter(purchaseEntity -> {
                    //只有新建和已分配的状态才可以被领取
                    if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                            || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    } else {
                        return false;
                    }
                }).map(purchaseEntity -> {
            //修改采购单的状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).forEach(purchaseEntity -> {
            //更新才采购单状态
            this.updateById(purchaseEntity);
            //更新采购需求详情状态
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>()
                    .eq("purchase_id", purchaseEntity.getId()));
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {
                purchaseDetailEntity.setPurchaseId(purchaseEntity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });
    }

    @Override
    public void done(PurchaseDoneVo doneVo) {
        Long purchaseId = doneVo.getId();
        //遍历出采购项是否有失败的，成功的采购项更新状态为完成采购,并入库库存，否则更新状态为采购失败
        List<Long> successIds = new ArrayList<Long>();
        List<Long> failIds = new ArrayList<Long>();
        Boolean[] success = {true};
        List<PurchaseDetailEntity> purchaseDetailEntities = doneVo.getItems().stream().map(purchaseItemDoneVo -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseItemDoneVo.getItemId());
            if (purchaseItemDoneVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                failIds.add(purchaseItemDoneVo.getItemId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            } else {
                successIds.add(purchaseItemDoneVo.getItemId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            }
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        //批量更新
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        //入库库存
        successIds.forEach(id -> {
            PurchaseDetailEntity entity = purchaseDetailService.getById(id);
            wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
        });

        //修改采购单的状态为完成采购或者有异常情况
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(failIds.size()>0?WareConstant.PurchaseStatusEnum.HASERROR.getCode():WareConstant.PurchaseStatusEnum.FINISH.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}